//
//  ShareManager.m
//  coldjoke-ios-client
//
//  Created by lai on 12-11-12.
//
//

#import "ShareManager.h"
#import "WXApi.h"
#import "UIViewController+PopupViewController.h"

@implementation ShareManager

SYNTHESIZE_SINGLETON_FOR_CLASS(ShareManager);

- (id)init
{
    self = [super init];
    if (self) {
        //初始化友盟分享
        sharetypeName = -1;
        socialData = [[UMSocialData alloc] initWithIdentifier:@"ColdJoke"];
        socialController = [[UMSocialControllerService alloc] initWithUMSocialData:socialData];
    }
    return self;
}

-(void)dealloc
{
    PP_RELEASE(socialController);
    PP_RELEASE(socialData);
    PP_RELEASE(mOwner);
    PP_RELEASE(mPlatform);
    [super dealloc];
}

-(void)weixinShare:(BaseUIViewController<ShareManagerDelegate>*)owner {
    mOwner = owner;
    //是否安装微信
    if (![WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"您还没有安装微信或者您的版本不支持分享功能!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }

    WXMediaMessage *message = [WXMediaMessage message];
    ShareModel *data = [owner SMDdata];
    message.description = data.text;
    message.title = data.title;   //长度不能超过512字节
    [message setThumbImage:data.thumbImage];
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = data.url;
    message.mediaObject = ext;
    SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    [data release];
    [WXApi sendReq:req];
}

-(void)weixinFriends:(BaseUIViewController<ShareManagerDelegate>*)owner {
    mOwner = owner;
    if (![WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"您还没有安装微信或者您的版本不支持分享功能!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }

    WXMediaMessage *message = [WXMediaMessage message];
    ShareModel *data = [owner SMDdata];
    message.title = data.title;
    message.description = data.text;
    [message setThumbImage:data.thumbImage];
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = data.url;
    message.mediaObject = ext;
    SendMessageToWXReq* req = [[[SendMessageToWXReq alloc] init]autorelease];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneTimeline;
    [data release];
    [WXApi sendReq:req];
}

-(void)sinaWeibo:(BaseUIViewController<ShareManagerDelegate>*)owner {
    mOwner = owner;
    [self publicOauthAndSendWeibo:UMSocialSnsTypeSina shareName:UMShareToSina];
}

-(void)tencentWeibo:(BaseUIViewController<ShareManagerDelegate>*)owner {
    mOwner = owner;
    [self publicOauthAndSendWeibo:UMSocialSnsTypeTenc shareName:UMShareToTencent];
}

-(void)douban:(BaseUIViewController<ShareManagerDelegate>*)owner {
    mOwner = owner;
    [self publicOauthAndSendWeibo:UMSocialSnsTypeDouban shareName:UMShareToDouban];
}

-(void)renren:(BaseUIViewController<ShareManagerDelegate>*)owner {
    mOwner = owner;
    [self publicOauthAndSendWeibo:UMSocialSnsTypeRenr shareName:UMShareToRenren];
}

-(void)qzone:(BaseUIViewController<ShareManagerDelegate>*)owner {
    mOwner = owner;
    [self publicOauthAndSendWeibo:UMSocialSnsTypeQzone shareName:UMShareToQzone];
}

-(void)smsMessage:(BaseUIViewController<ShareManagerDelegate>*)owner {
    mOwner = owner;
    ShareModel *data = [owner SMDdata];
    NSString *smsData = [NSString stringWithFormat:@"%@ %@ <内容来自于爱讲冷笑话>",data.text,data.url];
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
    Log(@"can send SMS [%d]", [messageClass canSendText]);
    if (messageClass != nil) {
        if ([messageClass canSendText]) {
            [self displaySMS:smsData];
        } else {
            [owner baseShowInfoHud:NSLocalizedString(@"设备没有短信功能", @"") andIsTop:NO];
        }
    }else{
        [owner baseShowInfoHud:NSLocalizedString(@"iOS版本过低，iOS4.0以上才支持程序内发送短信", @"") andIsTop:NO];
    }
    [data release];
}

#pragma mark -
#pragma mark -------友盟API和回调方法----

//授权和发送的公用方法
- (void)publicOauthAndSendWeibo:(UMSocialSnsType)platformName shareName:(NSString *)platformShareName
{
    Log(@"%@ oauth is nil? : %@",platformShareName,[socialData.socialAccount objectForKey:platformShareName] ) ;
    
    if ([socialData.socialAccount objectForKey:platformShareName] == nil) {
        Log(@"oauthing");
        socialController.soicalUIDelegate = self; //设置授权页面的委托
        UINavigationController *oauthController = [socialController getSocialOauthController:platformName];
        [mOwner presentModalViewController:oauthController animated:YES];
        mPlatform = platformShareName;
        sharetypeName = platformName;
    }else{
        Log(@"sending");
        [socialController.socialDataService setUMSocialDelegate:self]; //设置发送微博的委托
        ShareModel *data = [mOwner SMDdata];
        [socialController.socialDataService postSNSWithType:platformName usid:nil content:data.weiboText image:nil location:nil];
        [data release];
    }
}

//发送微博完成的回调方法
- (void)didFinishGetUMSocialDataResponse:(UMSocialResponseEntity *)response
{
    Log(@"account reponse : %@",response);
    if (response.responseType == UMSResponseShareToSNS) {
        if (response.responseCode == UMSResponseCodeSuccess) {
            [mOwner baseShowInfoHud:NSLocalizedString(@"发送成功", @"") andIsTop:NO];
        }else {
            NSString *msg = @"";
            if (response.responseCode == UMSResponseCodeShareRepeated) {
                msg = @"error:连续发送内容重复";
            }else if (response.responseCode == UMSResponseCodeGetNoUidFromOauth) {
                msg = @"error:授权错误";
            }else if (response.responseCode == UMSResponseCodeAccessTokenExpired) {
                msg = @"error:授权过期";
            }else if (response.responseCode == UMSResponseCodeNetworkError){
                msg = @"error:网络错误";
            }else{
                msg = response.message;
            }
            [mOwner baseShowInfoHud:NSLocalizedString(msg, @"") andIsTop:NO];
        }
    }
}

//授权完成的回调方法
- (void)didCloseUIViewController
{
    Log(@"done");
    if ([socialData.socialAccount objectForKey:mPlatform] == nil) {
        Log(@"nil");
        mPlatform = nil;
        return;
    }
    if (sharetypeName > 9 && sharetypeName < 15 ){
        Log(@"not nil");
        [socialController.socialDataService setUMSocialDelegate:self]; //设置发送微博的委托
        ShareModel *data = [mOwner SMDdata];
        [socialController.socialDataService postSNSWithType:sharetypeName usid:nil content:data.weiboText image:nil location:nil];
        [data release];
    }else{
        Log(@"failed");
    }
    sharetypeName = -1;
}

#pragma mark -
#pragma mark -------发送短信-----

- (void)displaySMS:(NSString *)message
{
    MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
    picker.messageComposeDelegate = self;
    //picker.navigationBar.tintColor= [UIColor blackColor];
    picker.body = message; // 默认信息内容
    // 默认收件人(可多个)
    //picker.recipients = [NSArray arrayWithObject:@"12345678901", nil];
    [mOwner presentModalViewController:picker animated:YES];
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    NSString *msg = nil;
    switch (result) {
        case MessageComposeResultCancelled:
        {
            msg = @"发送取消";
            [mOwner baseShowInfoHud:NSLocalizedString(msg, @"") andIsTop:NO];
            break;
        }
        case MessageComposeResultFailed:
        {
            msg = @"发送失败";
            [mOwner baseShowInfoHud:NSLocalizedString(msg, @"") andIsTop:NO];
            break;
        }
        default:
            break;
    }
    Log(@"res : %@", msg);
    [mOwner dismissModalViewControllerAnimated:YES];
}

-(void)copy:(NSString *)textToCopy {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = textToCopy;
}

@end
